﻿using iTool.Utils;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reactive.Subjects;
using System.Text;

namespace iTool.Cloud.NetCore
{
    public abstract class AbstractiToolSubject : AbstractiToolClientInfo
    {

        ConcurrentDictionary<string, Subject<string>> SubscribeDictionary { get; set; }

        protected AbstractiToolSubject()
        {
            this.SubscribeDictionary = new ConcurrentDictionary<string, Subject<string>>();

            this.OnReceiveEvent += (e, msg) => 
            {
                var entity = msg.TryToJObject();
                if (entity == null) return;

                if (entity.ContainsKey("Topic"))
                {
                    if (this.SubscribeDictionary.TryGetValue(entity["Topic"].ToString(), out var subject))
                    {
                        subject.OnNext(msg);
                    }
                }
            };

        }


        /// <summary>
        /// 监听指定Topic消息
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="action"></param>
        public void AddMessageListener(string topic, Action<string> action)
        {
            this.SubscribeDictionary.AddOrUpdate(topic, a => new Subject<string>(), (t, old) =>
            {
                old.OnCompleted();
                old?.Dispose();
                return new Subject<string>();
            });
        }


        /// <summary>
        /// 移除监听
        /// </summary>
        /// <param name="topic"></param>
        public void RemoveMessageListener(string topic)
        {
            if (this.SubscribeDictionary.TryRemove(topic, out var old))
            {
                old.OnCompleted();
                old.Dispose();
            }
        }

    }
}
